#!/bin/bash

DEF_GATEWAY=$1
CURR_DIR=$(cd `dirname $0`; pwd)
Auto_run=/etc/rc.local
rt_tables=/etc/iproute2/rt_tables
auto_add=`cat $Auto_run |grep -w "route del default" |wc -l`
chmod +x $Auto_run
ETH_NUM=`ls /etc/sysconfig/network-scripts/ifcfg-* | grep -v 'ifcfg-lo' | awk -F '-' '{print $NF}' | wc -l`
ACTION="add"
RULE="NET"

if [ $# -eq 0 ]; then
  echo "输入默认路由网关: sh $0 10.10.10.10"
  exit 1
fi

#if [ $# -ne 0 ]; then
#    if [ "$1" != "add" -a "$1" != "del" ]; then
#        echo "error"
#    else
#        ACTION="$1"
#    fi
#fi


function add_rule() {
  rule_num=`grep "NET" $rt_tables | wc -l`
  if [ $rule_num -eq $ETH_NUM ];then
      echo "$ETH_NUM 条路由策略已存在"
  else
      for ((j=1;j<=$ETH_NUM;j++))
      do
        echo "添加NET路由策略" && echo 25$j ${RULE}$j >> $rt_tables
      done
  fi
}

add_rule

count=0
for i in `ls /etc/sysconfig/network-scripts/ifcfg-* | grep -v 'ifcfg-lo'`
do
  count=$((count+1))
  DEVICE=`cat $i| grep -E "DEVICE" | awk -F '=' '{print $NF}'`
  IPADDR=`cat $i| grep -E "IPADDR" | awk -F '=' '{print $NF}'`
  GATEWAY=`cat $i| grep -E "GATEWAY" | awk -F '=' '{print $NF}'`
  NETMASK=`cat $i| grep -E "NETMASK" | awk -F '=' '{print $NF}'`
  
  echo "ip route ${ACTION} ${NETMASK} dev ${DEVICE} src ${IPADDR} table ${RULE}$count"
  ip route ${ACTION} ${NETMASK} dev ${DEVICE} src ${IPADDR} table ${RULE}$count
  echo "ip route ${ACTION} default via ${GATEWAY} table ${RULE}$count"
  ip route ${ACTION} default via ${GATEWAY} table ${RULE}$count
  echo "ip rule ${ACTION} from ${IPADDR} table ${RULE}$count"
  ip rule ${ACTION} from ${IPADDR} table ${RULE}$count
done

echo "ip route add default via ${DEF_GATEWAY}"
ip route add default via ${DEF_GATEWAY}

if [ $auto_add -eq "0" ]; then
echo "开机自动添加路由策略"
echo "sh $CURR_DIR/$0 $DEF_GATEWAY"  >> $Auto_run
echo "route del default && route add default $DEF_GATEWAY" >> $Auto_run
fi
